package com.yc.framework.interceptor;

import com.alibaba.fastjson2.JSON;
import com.yc.common.core.domain.AjaxResult;
import com.yc.common.utils.WebUtil;
import com.yc.system.service.IpLimitService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * IP封禁拦截器 - 专门负责拦截已被封禁的IP
 */
@Component
public class IpBanInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(IpBanInterceptor.class);

    @Autowired
    private IpLimitService ipLimitService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ipAddress = WebUtil.getIpAddr();

        // 检查IP是否被禁止
        if (ipLimitService.isIpBanned(ipAddress)) {
            log.warn("拦截到被禁止的IP: {}, URI: {}", ipAddress, request.getRequestURI());
            handleBannedIp(response);
            return false;
        }

        return true;
    }

    private void handleBannedIp(HttpServletResponse response) throws IOException {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.setContentType("application/json;charset=UTF-8");

        AjaxResult result = AjaxResult.error(HttpStatus.FORBIDDEN.value(),
                "您的IP已被临时禁止访问，请稍后再试");

        response.getWriter().write(JSON.toJSONString(result));
    }
}